package mongoDB.group;

import static org.springframework.data.mongodb.core.aggregation.Aggregation.group;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.mongodb.AggregationOutput;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;

/**
 * 
 * @Title: TestMongoSpiring.java
 * @Package mongoDB.group
 * @Description: spring 分组实现
 *               db.appUser.aggregate([{"$group":{_id:"$userid",count:{$sum:1}}},{$sort:{count:-1}}])
 * @author 刘伟 15818570028@163.com
 * @date 2017年2月23日 上午11:45:55
 * @version V1.0
 */

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring-mongodb.xml" })
public class TestMongoSpiring {
	@Autowired
	private MongoTemplate mt;

	/**
	 * 
	 * @Title: test1 根据citycode分组
	 * @Description: 基本分组使用
	 */
	@Test
	public void test1() {
		Aggregation agg = newAggregation(group("citycode").count().as("count"));
		AggregationResults<AppUser> results = mt.aggregate(agg, "user_start_app", AppUser.class);
		List<AppUser> tagCount = results.getMappedResults();
		System.out.println(tagCount.get(0));
	}
	/**
	 * 
	 * @Title: test3 根据citycode 前四位分组
	 * @Description: 方式二，
	 */
	@Test
	public void test2() {
		Aggregation agg = newAggregation(Aggregation.project("citycode")
                .andExpression("substr(citycode,0,10)").as("citycode"),group(
				"citycode").count().as("count"));
		AggregationResults<AppUser> results = mt.aggregate(agg, "user_start_app", AppUser.class);
		List<AppUser> tagCount = results.getMappedResults();
		System.out.println(tagCount.get(0));
	}

	/**
	 * 
	 * @Title: test3 根据citycode 前四位分组
	 * @Description: 方式二，使用原生态mongodb语法
	 */
	@Test
	public void test3() {

		List<DBObject> pipeline = new ArrayList<DBObject>();
		String groupStr = "{'$group':{_id:{'$substr' : ['$citycode',0 ,4]},count:{$sum:1}}},{$sort:{count:-1}}";
		DBObject group = (DBObject) JSON.parse(groupStr);
		pipeline.add(group);
		/* 查看Group结果 */
		AggregationOutput output = mt.getCollection("user_start_app").aggregate(pipeline);
		System.out.println(output.results());
	}

}
